package com.next

import grails.transaction.Transactional
import org.springframework.security.access.annotation.Secured

import java.util.regex.*

import static org.springframework.http.HttpStatus.*

@Secured(['ROLE_ADMINISTRATOR', 'ROLE_COMPANY_ADMINISTRATOR', 'ROLE_COMPANY_USER'])
@Transactional(readOnly = true)
class FlexFieldInstanceController
{

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]
    def springSecurityService

    @Secured(['ROLE_ADMINISTRATOR'])
    def index(Integer max)
    {
        params.max = Math.min(max ?: 10, 100)
        respond FlexFieldInstance.list(params), model: [flexFieldInstanceCount: FlexFieldInstance.count()]
    }

    def show(FlexFieldInstance flexFieldInstance)
    {
        respond flexFieldInstance
    }

    def create()
    {
        respond new FlexFieldInstance(params)
    }

    @Transactional
    def save(FlexFieldInstance flexFieldInstance)
    {
        if (flexFieldInstance == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (flexFieldInstance.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond flexFieldInstance.errors, view: 'create'
            return
        }

        flexFieldInstance.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'flexFieldInstance.label', default: 'FlexFieldInstance'), flexFieldInstance.id])
                redirect flexFieldInstance
            }
            '*' { respond flexFieldInstance, [status: CREATED] }
        }
    }

    def edit(FlexFieldInstance flexFieldInstance)
    {
        def username = springSecurityService?.getPrincipal()?.username
        def user = User.findByUsername(username)
        def targetUri = request.getHeader("referer")
        def permission = false

        TeamRole editTeamRole = TeamRole.findByName('Edit')

        if (flexFieldInstance?.user?.id == user.id)
        {
            permission = true
        }
        else if (params['teamName'])
        {
            def flexFieldPermission
            switch (params['teamName'])
            {
            case "contactTeam":
                flexFieldPermission = ContactTeam.findByContactAndUser(flexFieldInstance?.contact, user)?.flexFieldPermission
                if (flexFieldPermission?.id == editTeamRole.id)
                {
                    permission = true
                }
                break
            case "accountTeam":
                flexFieldPermission = AccountTeam.findByAccountAndUser(flexFieldInstance?.account, user)?.flexFieldPermission
                if (flexFieldPermission?.id == editTeamRole.id)
                {
                    permission = true
                }
                break
            case "opportunityTeam":
                flexFieldPermission = OpportunityTeam.findByOpportunityAndUser(flexFieldInstance?.opportunity, user)?.flexFieldPermission
                if (flexFieldPermission?.id == editTeamRole.id)
                {
                    permission = true
                }
                break
            case "campaignTeam":
                flexFieldPermission = CampaignTeam.findByCampaignAndUser(flexFieldInstance?.campaign, user)?.flexFieldPermission
                if (flexFieldPermission?.id == editTeamRole.id)
                {
                    permission = true
                }
                break
            case "issueTeam":
                flexFieldPermission = IssueTeam.findByIssueAndUser(flexFieldInstance?.issue, user)?.flexFieldPermission
                if (flexFieldPermission?.id == editTeamRole.id)
                {
                    permission = true
                }
                break
            case "assetTeam":
                flexFieldPermission = AssetTeam.findByAssetAndUser(flexFieldInstance?.asset, user)?.flexFieldPermission
                if (flexFieldPermission?.id == editTeamRole.id)
                {
                    permission = true
                }
                break
            }
        }

        if (permission)
        {
            respond flexFieldInstance, model: [targetUri: targetUri]
        }
        else
        {
            flash.message = "没有编辑权限"
            redirect uri: request.getHeader("referer")
        }
    }

    @Transactional
    def update(FlexFieldInstance flexFieldInstance)
    {
        if (flexFieldInstance == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (flexFieldInstance.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond flexFieldInstance.errors, view: 'edit'
            return
        }
        if (flexFieldInstance?.value && flexFieldInstance?.field?.valueConstraints)
        {
            if (!(flexFieldInstance.value.matches(flexFieldInstance.field.valueConstraints)))
            {
                flash.message = "定制字段校验未通过"
                respond flexFieldInstance, model: [targetUri: params['targetUri']], view: 'edit'
                return
            }
        }

        flexFieldInstance.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'flexFieldInstance.label', default: 'FlexFieldInstance'), flexFieldInstance.id])
                // redirect flexFieldInstance
                redirect uri: params['targetUri']
            }
            '*' { respond flexFieldInstance, [status: OK] }
        }
    }

    @Transactional
    def delete(FlexFieldInstance flexFieldInstance)
    {

        if (flexFieldInstance == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        flexFieldInstance.delete flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'flexFieldInstance.label', default: 'FlexFieldInstance'), flexFieldInstance.id])
                // redirect action:"index", method:"GET"
                redirect uri: request.getHeader("referer")
            }
            '*' { render status: NO_CONTENT }
        }
    }

    protected void notFound()
    {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'flexFieldInstance.label', default: 'FlexFieldInstance'), params.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NOT_FOUND }
        }
    }
}
